package org.ytor.core.sysapi.permission.logic;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ytor.common.util.Colls;
import org.ytor.common.util.tree.Trees;
import org.ytor.core.sysapi.dict.service.IDictParse;
import org.ytor.core.sqlflow.BaseLogic;
import org.ytor.core.sysapi.permission.model.SysPermission;
import org.ytor.core.sysapi.permission.repository.SysPermissionRepository;
import org.ytor.core.sysapi.permission.resp.SysPermissionResp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * created by System on 2025年5月22日 20:45:43
 * <br/>
 * SysPermission服务
 * <br/>
 */
@Service
@RequiredArgsConstructor
public class SysPermissionLogic extends BaseLogic<SysPermission, SysPermissionRepository> {

    private final IDictParse dictParse;

    public List<SysPermissionResp> queryByPid(String pid) {
        return repository.queryByPid(pid);
    }

    public List<Map<String, Object>> tree(String permissionName) {

        List<SysPermission> list = repository.queryList();
        List<SysPermissionResp> respList = list.stream().map(SysPermission::toResp).toList();
        List<SysPermissionResp> tree = Trees.toTree(respList, permissionName);

        List<Map<String, Object>> departTree = new ArrayList<>();
        for (SysPermissionResp sysPermissionResp : tree) {
            departTree.add(parseDict(sysPermissionResp));
        }

        return departTree;
    }

    private Map<String, Object> parseDict(SysPermissionResp resp) {
        Map<String, Object> translatedDepart = dictParse.translate(resp);
        if (Colls.isEmpty(resp.getChildren())) {
            return translatedDepart;
        }
        List<Map<String, Object>> children = new ArrayList<>();
        for (SysPermissionResp child : resp.getChildren()) {
            children.add(parseDict(child));
        }
        translatedDepart.put("children", children);
        return translatedDepart;
    }
}